package com.freewater.cargotracker.infrastructure.persistence.mybatis.repository;

import com.freewater.cargotracker.domain.model.cargo.TrackingId;
import com.freewater.cargotracker.domain.model.customer.Customer;
import com.freewater.cargotracker.domain.model.customer.CustomerNo;
import com.freewater.cargotracker.domain.model.customer.CustomerRepository;
import com.freewater.cargotracker.domain.model.customer.Role;
import com.freewater.cargotracker.infrastructure.persistence.mybatis.converter.CustomerConverter;
import com.freewater.cargotracker.infrastructure.persistence.mybatis.dbobject.CustomerPO;
import com.freewater.cargotracker.infrastructure.persistence.mybatis.mapper.CustomerMapper;
import org.springframework.stereotype.Repository;

import java.util.Map;

@Repository
public class CustomerRepositoryImpl implements CustomerRepository {

    private final CustomerMapper customerMapper;

    public CustomerRepositoryImpl(CustomerMapper customerMapper) {
        this.customerMapper = customerMapper;
    }

    @Override
    public void save(Customer customer) {
        final CustomerPO customerPO = CustomerConverter.serialize(customer);
        this.customerMapper.insert(customerPO);
        customer.setId(customerPO.getId());
    }

    @Override
    public Customer findByCustomerNo(CustomerNo customerNo) {
        final CustomerPO customerPO = this.customerMapper.findByCustomerNo(customerNo.getIdString());
        if (customerPO == null) {
            return null;
        }
        final Customer customer = CustomerConverter.deserialize(customerPO);
        return customer;
    }

    @Override
    public Customer findByName(String name) {
        final CustomerPO customerPO = this.customerMapper.findByName(name);
        if (customerPO == null) {
            return null;
        }
        final Customer customer = CustomerConverter.deserialize(customerPO);
        return customer;
    }

    @Override
    public Map<Role, Customer> findCustomersOfCargo(TrackingId trackingId) {
        return null;
    }
}
